import {Component, OnInit} from '@angular/core';
import {CdkDragDrop, moveItemInArray} from '@angular/cdk/drag-drop';
import {NzMessageService} from 'ng-zorro-antd/message';
import {NzModalService} from 'ng-zorro-antd/modal';
import {NzUploadFile} from 'ng-zorro-antd/upload';
import {ActivatedRoute, Router} from '@angular/router';
import {AssessPriceService} from '../../assess-price.service';
import {NzImageService} from 'ng-zorro-antd/image';
import {PreviewOptionImgRemarkComponent} from '../preview-option-img-remark/preview-option-img-remark.component';

// 题目
interface Question {
  id: string; // 题目id
  questionName: string; // 题目名称
  selectType: 0 | 1; // 题目是多选还是单选
  isRequired: boolean; // 是否是必选
  options: Option[]; // 选项
}

// 选项
interface Option {
  id: string; // 选项id
  optionName: string; // 选项名称
  selectAble: boolean; // 是否可选
  invalidCause: string; // 不可选理由
  used: boolean; // 是否是二手
  questionId: any; // 要跳转的题目的id
  optionRemark: string; // 选项描述
  optionImages: any[]; // 选项图片
}

@Component({
  selector: 'app-assess-price-template',
  templateUrl: './assess-price-template.component.html',
  styleUrls: ['./assess-price-template.component.scss']
})
export class AssessPriceTemplateComponent implements OnInit {
  // 是否已经保存
  isSaved = false;
  // 模版Id
  templateId = null;
  // 模版信息
  template = {
    templateName: '',
    templateRemark: '',
  };
  // 题目列表
  questionList: Question[] = [];
  // 可以选择跳转的题目列表
  availableJumpIndexList: any[] = [];
  // 预览模态框显隐
  previewAssessPriceVisible = false;
  // 选择题目
  pickQuestion = {
    visible: false,
    questionId: '',
    selectType: 0,
    isRequired: 0,
  };
  // 选择问题后查询到的问题详情，用于选项显示选择
  checkedQuestion: any;
  // 可选题目列表
  questionOptions: any[] = [];
  optionCheckedIds = new Set();

  // 是否是基础修改，可以增加和删除等
  isBaseModify = true;
  // 是否是只读
  readonly = false;
  // 被引用后的编辑操作
  refModify = false;

  constructor(
    private message: NzMessageService,
    private nzModalService: NzModalService,
    private activatedRoute: ActivatedRoute,
    private assessPriceService: AssessPriceService,
    private nzImageService: NzImageService,
    private router: Router,
  ) {
  }

  ngOnInit(): void {
    if (this.activatedRoute.snapshot.queryParams.operationType === 'modify') {
      this.initModifyData();
      this.isBaseModify = true;
    }
    if (this.activatedRoute.snapshot.queryParams.operationType === 'view') {
      this.readonly = true;
      this.initModifyData();
    }
    if (this.activatedRoute.snapshot.queryParams.operationType === 'copy') {
      this.initModifyData();
      this.templateId = null;
      this.isBaseModify = true;
      this.refModify = false;
      this.readonly = false;
    }
    this.filterAvailableJumpQuestion(0);
    this.getQuestionOptions();
  }

  getQuestionOptions() {
    return this.assessPriceService.getQuestionList(1, 9999, '', '', '').then((res: any) => {
      if (res.code === 0) {
        this.questionOptions = res.data.list.records;
      }
    });
  }

  // 初始化修改数据
  initModifyData() {
    const data = JSON.parse(this.activatedRoute.snapshot.queryParams.templateInfo);
    if (data.modelNum * 1 > 0) {
      this.readonly = true;
      this.refModify = true;
      this.isBaseModify = false;
    }
    this.template.templateName = data.title;
    this.template.templateRemark = data.remarks;
    this.isBaseModify = data.modelNum === 0;
    this.questionList = JSON.parse(data.context).map((i: any) => {
      return {...i, isRequired: i.isRequired * 1 === 1};
    });
    this.templateId = data.id;
  }

  // 检查是否有空题目
  verifyNullQuestion() {
    return new Promise((resolve, reject) => {
      if (!this.questionList.length) {
        return resolve();
      }
      if (this.questionList.some(spec => spec.questionName === '')) {
        return reject('存在未填写的题目');
      }
      // tslint:disable-next-line:prefer-for-of
      for (let i = 0; i < this.questionList.length; i++) {
        if (this.verifyNullOption(this.questionList[i].options)) {
          return reject('存在未填写的选项');
        }
        if (!this.questionList[i].options.length) {
          return reject('每个题目至少需要有一个选项');
        }
      }
      resolve();
    });
  }

  // 检查是否有空选项
  verifyNullOption(options: Option[]) {
    if (options.length) {
      return options.some(option => option.optionName === '');
    } else {
      return false;
    }
  }

  // 添加题目
  addQuestion() {
    if (!this.checkedQuestion) {
      this.message.warning('请选择题目');
      return;
    }
    if (!this.optionCheckedIds.size) {
      this.message.warning('至少需要选中一个选项');
      return;
    }
    if (this.questionList.some(i => i.id === this.pickQuestion.questionId)) {
      this.message.warning('一个问题只能添加一次');
      return;
    }
    this.questionList.push({
      id: this.checkedQuestion.recycleEvalQuestion.id,
      questionName: this.checkedQuestion.recycleEvalQuestion.questionName,
      selectType: this.checkedQuestion.recycleEvalQuestion.selectType,
      isRequired: this.checkedQuestion.recycleEvalQuestion.isRequired === 1,
      options: this.checkedQuestion.recycleEvalOptions.filter((o: any) => this.optionCheckedIds.has(o.id)),
    });
    this.violenceSort();
    this.hidePickQuestionModal();
  }

  questionOptionDisabled(id: any) {
    return this.questionList.some(i => i.id === id);
  }

  // 拖拽题目
  dropQuestion(event: any) {
    if (this.readonly) {
      return;
    }
    // console.log(event.previousIndex, event.currentIndex);
    const firstNotRequiredIndex = this.questionList.findIndex(q => !q.isRequired);
    // console.log(firstNotRequiredIndex);
    if (firstNotRequiredIndex > -1 && event.previousIndex >= firstNotRequiredIndex && event.currentIndex < firstNotRequiredIndex) {
      this.message.warning('非必选题目只能在必选题目后面');
      return;
    }
    if (firstNotRequiredIndex > -1 && this.questionList[event.previousIndex].isRequired && event.currentIndex >= firstNotRequiredIndex) {
      this.message.warning('必选题目只能在非必选题目前面');
      return;
    }
    if (this.questionList.some(q => q.options.some(o => o.questionId))) {
      this.nzModalService.confirm({
        nzTitle: '警告',
        nzContent: '<b>重新排序将会清除所有的跳转，确定要继续吗?</b>',
        nzOkText: '确定',
        nzOkType: 'primary',
        nzOkDanger: true,
        nzOnOk: () => {
          this.deleteRelation();
          moveItemInArray(this.questionList, event.previousIndex, event.currentIndex);
          this.violenceSort();
        },
        nzCancelText: '取消',
        nzOnCancel: () => {
        }
      });
    } else {
      moveItemInArray(this.questionList, event.previousIndex, event.currentIndex);
      this.violenceSort();
    }
  }


  // 拖拽选项
  dropOption(event: any, index: number) {
    moveItemInArray(this.questionList[index].options, event.previousIndex, event.currentIndex);
  }

  // 强制排序，非必选
  violenceSort() {
    if (this.questionList.length > 1) {
      this.questionList = [
        ...this.questionList.filter(question => question.isRequired),
        ...this.questionList.filter(question => !question.isRequired)
      ];
    }
  }

  // 过滤可选的题目
  filterAvailableJumpQuestion(index: number) {
    const list: any[] = [];
    this.questionList.forEach((item, i) => {
      if (i > index && item.questionName) {
        // originalIndex在原始表格中的位置
        list.push({...item, originalIndex: i});
      }
    });
    list.push({questionName: '结束', id: 'end', originalIndex: this.questionList.length});
    this.availableJumpIndexList = list;
  }

  // 删除题目
  removeQuestion(questionIndex: number, questionId: string) {
    this.deleteRelation(questionId);
    this.questionList.splice(questionIndex, 1);
  }

  // 解除关联
  deleteRelation(questionId?: string) {
    this.questionList.forEach((question) => {
      question.options.forEach(option => {
        if (questionId) {
          option.questionId = option.questionId === questionId ? null : option.questionId;
        } else {
          option.questionId = '';
        }
      });
    });
  }

  // 显示预览模态框
  showPreviewModal() {
    this.previewAssessPriceVisible = true;
  }

  // 离开
  back() {
    this.router.navigate(['/aisi-recyc/assessPriceTemplateList']);
  }

  // 显示选项描述和图片
  showOptionRemarkModal(question: any, option: any, $event: any) {
    let details: any[] = [];
    if (question?.options) {
      question.options.forEach((o: any) => {
        if (o.optionImages || o.optionRemark) {
          details = [...details, ...o.optionImages.split(',').map((v: any) => ({
            id: o.id,
            name: o.optionName,
            url: v,
            remark: o.optionRemark
          }))];
        }
      });
    } else {
      question.forEach((o: any) => {
        if (o.optionImages || o.optionRemark) {
          details = [...details, ...o.optionImages.split(',').map((v: any) => ({
            id: o.id,
            name: o.optionName,
            url: v,
            remark: o.optionRemark
          }))];
        }
      });
    }
    const index = details.findIndex(d => d.id === option.id);
    const modal = this.nzModalService.create({
      nzTitle: question.questionName,
      nzContent: PreviewOptionImgRemarkComponent,
      nzComponentParams: {
        details,
        index
      },
      nzFooter: null,
      nzMaskClosable: true,
    });
    $event.stopPropagation();
    $event.preventDefault();
    $event.returnValue = false;
  }

  // 显示选择问题模态框
  showPickQuestionModal() {
    this.pickQuestion = {
      visible: true,
      questionId: '',
      selectType: 0,
      isRequired: 0,
    };
  }

  // 隐藏选项描述和图片
  hidePickQuestionModal() {
    this.pickQuestion = {
      visible: false,
      questionId: '',
      selectType: 0,
      isRequired: 0,
    };
    this.checkedQuestion = null;
  }

  pickQuestionChange() {
    this.checkedQuestion = null;
    this.pickQuestion.selectType = 0;
    this.pickQuestion.isRequired = 0;
    this.questionOptions.forEach(i => {
      if (i.id + '' === this.pickQuestion.questionId + '') {
        this.pickQuestion.selectType = i.selectType;
        this.pickQuestion.isRequired = i.isRequired;
      }
    });
    this.assessPriceService.getQuestionDetail(this.pickQuestion.questionId).then((res: any) => {
      if (res.code === 0) {
        this.optionCheckedIds = new Set();
        this.checkedQuestion = res.data;
      }
    });
  }

  // 提交
  submitTemplate() {
    if (!this.template.templateName.trim()) {
      this.message.error('请输入模版名称');
      return;
    }
    this.verifyNullQuestion().then(() => {
      const problemId = this.questionList.map(q => q.id);
      let optionId: any[] = [];
      this.questionList.forEach(q => {
        optionId = [...optionId, q.options.map(o => o.id)];
      });
      this.assessPriceService.addAndModifyTemplate(
        this.template.templateName.trim(),
        this.template.templateRemark,
        JSON.stringify(this.questionList),
        problemId.join(','),
        optionId.join(','),
        this.templateId,
      ).then((res: any) => {
        if (res.code === 0) {
          this.message.success('操作成功');
          this.isSaved = true;
          this.router.navigate(['/aisi-recyc/assessPriceTemplateList']);
        } else {
          this.message.error(res.message);
        }
      }).catch(() => {
        this.message.error('操作异常');
      });
    }).catch(err => {
      this.message.error(err);
    });
  }

  // 预览和保存按钮显示状态
  previewAndSaveBtnVisible() {
    return this.questionList.length;
  }

  async refreshQuestionOptions() {
    await this.getQuestionOptions();
    this.pickQuestionChange();
  }

  // 获取选项选中状态
  optionCheckStatus() {
    if (this.optionCheckedIds.size === this.checkedQuestion.recycleEvalOptions.length) {
      this.optionCheckedIds = new Set();
    } else {
      this.optionCheckedIds = new Set(this.checkedQuestion.recycleEvalOptions.map((i: any) => i.id));
    }
  }

  // 获取选项选中状态
  optionCheckedChange(a: any) {
    if (this.optionCheckedIds.has(a)) {
      this.optionCheckedIds.delete(a);
    } else {
      this.optionCheckedIds.add(a);
    }
  }

}
